import React, { lazy, Suspense } from 'react';
import { Switch, BrowserRouter as Router, Route, Redirect } from 'react-router-dom';
import routerConfig from './config';
import store from '../store';

// 判断用户是否已登录的函数
const isAuthenticated = () => {
  const token = store.getState().auth.token;
  return !!token;
};

// 处理认证和重定向的 ProtectedRoute 组件
const ProtectedRoute = ({ component: Component, ...rest }) => (
  <Route
    {...rest}
    render={(props) =>
      isAuthenticated() ? (
        <Suspense fallback={<div>加载中...</div>}>
          <Component {...props} />
        </Suspense>
      ) : (
        <Redirect to="/login" />
      )
    }
  />
);

const RenderRoutes = ({ routes }) => {
  const renderRouteMap = (routes) => {
    return routes.map((route, index) => {
      const LoadableComponent = route.lazyComponent ? lazy(() => route.lazyComponent()) : route.component;

      // 如果是登录页面并且用户已认证，则重定向到首页
      const RouteComponent = route.path === '/login' && isAuthenticated()
        ? () => <Redirect to="/home" />
        : (props) => (
          route.path !== '/login'
            ? <ProtectedRoute component={LoadableComponent} {...props} />
            : <Suspense fallback={<div>加载中...</div>}><LoadableComponent {...props} /></Suspense>
        );
      
      return (
        <Route
          key={index}
          exact={route.exact}
          path={route.path}
          render={(props) => (
            <RouteComponent {...props} />
          )}
        />
      );
    });
  };

  return (
    <Router>
      <Switch>
        <Redirect from="/" exact
          to="/home" />
        {renderRouteMap(routes)}
        <Redirect to="/404" />
      </Switch>
    </Router>
  );
};

const MainRouter = () => {
  return <RenderRoutes routes={routerConfig} />;
};

export default MainRouter;
